//
//  HMOAuthViewController.swift
//  swift微博项目
//
//  Created by huodian on 16/9/25.
//  Copyright © 2016年 huodian. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMOAuthViewController: UIViewController {

    lazy var webview = UIWebView()
    
    override func loadView() {
        
        webview.isOpaque = false
        
        webview.delegate = self
        
        self.view = webview
        
       backViewController()
        
        loadOAuthPag()
        
    }
    
    
    func backViewController() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注销", imageNamed: nil, target: self, action: #selector(clickOauthleftItem))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageNamed: nil, target: self, action: #selector(clickOauthrightItem))
        
    }
    
    func clickOauthrightItem() {
        
        //自动填充
        
        let jsString = "document.getElementById('userId').value = '13378643458', document.getElementById('passwd').value = 'yhc43327' "
        
        webview.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
    func clickOauthleftItem()  {
        
        self.dismiss(animated: true, completion: nil)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
   
        
    }
    
    func loadOAuthPag(){
        
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "3406198782" + "&redirect_uri=" + "http://www.itheima.com"
        
        let url = URL(string: urlStr)
        
        let request = URLRequest(url: url!)
        
        
        webview.loadRequest(request)
        
        
        
    }

   
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    

}
extension HMOAuthViewController: UIWebViewDelegate{
    
    
    func  webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
  
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //绝对路劲
        let urlString = request.url?.absoluteString ?? ""
        
        //http://www.itheima.com/?code=71e33a0143d3ea89c189513cac17b594
        let flag = "code="
        
        if (urlString.contains(flag)){
            
            let str = request.url?.query ?? ""
            
            let codee  = (str as NSString).substring(from: flag.characters.count)
           
            HMUserAccessViewModel.shareUserAccess.loadTheToken(code: codee, Finish: { (sucess) in
                
                if !sucess {
                    
                    SVProgressHUD.showError(withStatus: "你大爷的,怎么又没有网了")
                    return
                }
                
                print("数据获取成功")
                
            })
            
         //  loadTheToken(code: codee)
            //由于只关心拿到code 所以返回false
            return false
        }
        
    
        
        return true
        
    }
/*
    func loadTheToken(code:String) {
        //获取授权
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        //拼接参数
        let paramear = ["client_id" : client_id,
                        "client_secret" : client_secret,
                        "grant_type" : "authorization_code",
                        "code" : code,
                        "redirect_uri" : redirect_uri
        ]
        
        HMNetWorking.shareNetWorking.requset(method: .POST, url: urlStr, parameters: paramear) { (responsedObject, error ) in
            
            if error != nil {
                
                print(error)
                return
                
            }
           print("qibsbifs",responsedObject)
            self.loadUserMessage(dict: responsedObject as! [String:Any])
        }
    
        
        
    }
    
    func loadUserMessage(dict:[String:Any])
    {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        
        let paramar = ["access_token":access_token,
                        "uid":uid]
        
        HMNetWorking.shareNetWorking.requset(method: .GET, url: urlString, parameters: paramar) { (responsedObject, error) in
            
            if error != nil {
                
                
                return
                
            }
            
            
            
            var dic = responsedObject as! [String:Any]
            
            //拼接字典
            for dicValue in dict {
                
                dic[dicValue.key] = dicValue.value
                
                
            }
            
              print("qibsbifs",dict)
            let userAccess = HMUserAccessModel(dict: dic)
            
            print(userAccess)
            
           self.saveTheUserAccess(Model: userAccess)
            
        }
        
      
    }
    
    func saveTheUserAccess(Model:HMUserAccessModel){
        
        let url = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("sear.plist")
        
        print(url)
        
        NSKeyedArchiver.archiveRootObject(Model, toFile: url)
        
        
    }
 
 */
}
